package com.skynet.supervision.config;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.skynet.supervision.utils.Strings;
import lombok.val;

import java.io.IOException;

public final class JacksonBooleanDeserializer extends JsonDeserializer<Boolean> {
    public static final JacksonBooleanDeserializer INSTANCE = new JacksonBooleanDeserializer();
    @Override
    public Boolean deserialize(JsonParser p, DeserializationContext ctx) throws IOException, JsonProcessingException {
        val pt = p.currentToken();
        if(pt==JsonToken.VALUE_NULL){
            return null;
        }
        if(pt==JsonToken.VALUE_FALSE){
            return false;
        }
        if(pt==JsonToken.VALUE_TRUE){
            return true;
        }
        throw new JsonParseException(p, Strings.sprintf(" {} 不是合法的Boolean参数", p.getCurrentName()));
    }
}
